<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区 -->
        <el-card>
            <!-- 警告区域 -->
            <el-alert title="添加商品信息" show-icon type="info" center :closable="false" />
            <!-- 步骤条 -->
            <el-steps style="width: 100%;" :active="activeIndex - 0" align-center finish-status="success">
                <el-step title="基本信息" />
                <el-step title="商品参数" />
                <el-step title="商品属性" />
                <el-step title="商品照片" />
                <el-step title="商品内容" />
                <el-step title="完成" />
            </el-steps>
            <!-- tab栏区域 -->
            <el-form ref="addFormRef" style="max-width: 600px" :model="addForm" :rules="addFormRules" label-width="auto"
                label-position="top">
                <el-tabs :before-leave="beforeTabLeave" v-model="activeIndex" :tab-position="'left'" class="demo-tabs"
                    @tab-click="tabClicked">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addForm.goods_name" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="addForm.goods_price" type="number" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="addForm.goods_weight" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="addForm.goods_number" type="number" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="cateProps"
                                @change="handleChange" placeholder="请选择" style="width: 250px;" />
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <!-- 渲染表单的item项 -->
                        <el-form-item :label="item.attr_name" :key="item.attr_id"
                            v-for="(item, index) in manyTableData">
                            <!-- 复选框 -->
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox border :label="item" v-for="(item, index) in item.attr_vals"
                                    :key="index" />
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <!-- 渲染表单的item项 -->
                        <el-form-item :label="item.attr_name" :key="item.attr_id"
                            v-for="(item, index) in onlyTableData">
                            <!--  -->
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品照片" name="3">
                        <!-- action 图片上传api地址 -->
                        <el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove"
                            list-type="picture" :headers="headerObj" :on-success="handleSuccess">
                            <el-button type="primary">上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <!-- 富文本编辑组件 -->
                        <QuillEditor v-model:content="addForm.good_introduce" contentType="html" theme="snow"
                            :options="editorOptions" class="my-quill-editor" />
                        <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
        <!-- 图片预览 -->
        <el-dialog v-model="previewVisible" title="图片预览" width="50%">
            <img :src="previewPath" alt="" class="img">
        </el-dialog>
    </div>
</template>
<script>
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import _ from "lodash"
export default {
    components: {
        QuillEditor
    },
    data() {
        return {
            activeIndex: '0',
            cateList: [],
            //添加商品的表单数据对象
            addForm: {
                goods_price: 0,
                goods_name: '',
                goods_weight: 0,
                goods_number: 0,
                // 商品所属分类数组
                goods_cat: [],
                // 图片数组
                pics: [],
                // 商品详情
                goods_introduce: '',
                attrs: []
            },
            addFormRules: {
                goods_name: [{
                    required: true,
                    message: '请输入商品名称',
                    trigger: 'blur'
                },],
                goods_price: [{
                    required: true,
                    message: '请输入商品价格',
                    trigger: 'blur'
                },],
                goods_weight: [{
                    required: true,
                    message: '请输入商品重量',
                    trigger: 'blur'
                },],
                goods_number: [{
                    required: true,
                    message: '请输入商品数量',
                    trigger: 'blur'
                },],
                goods_cat: [{
                    required: true,
                    message: '请选择商品分类',
                    trigger: 'blur'
                },],
            },
            cateProps: {
                value: 'cat_id',
                label: 'cat_name',
                children: 'children',
                expandTrigger: 'hover'
            },
            // 动态参数
            manyTableData: [],
            // 静态属性
            onlyTableData: [],
            // 上传地址
            uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
            // 图片上传组件请求头
            headerObj: {
                Authorization: window.sessionStorage.getItem('token')
            },
            previewPath: '',
            previewVisible: false,
            // 富文本编辑器配置
            editorOptions: {
                theme: 'snow',
                placeholder: '请输入商品详细介绍...',
                modules: {
                    toolbar: [
                        ['bold', 'italic', 'underline', 'strike'], // 加粗、斜体、下划线、删除线
                        [{
                            'header': 1
                        }, {
                            'header': 2
                        }], // 标题1、标题2
                        [{
                            'list': 'ordered'
                        }, {
                            'list': 'bullet'
                        }], // 有序列表、无序列表
                        [{
                            'indent': '-1'
                        }, {
                            'indent': '+1'
                        }], // 减少缩进、增加缩进
                        [{
                            'direction': 'rtl'
                        }], // 文本方向
                        [{
                            'color': []
                        }, {
                            'background': []
                        }], // 文本颜色、背景颜色
                        [{
                            'font': []
                        }], // 字体
                        [{
                            'align': []
                        }], // 对齐方式
                        ['link', 'image'], // 链接、图片
                        ['clean'] // 清除格式
                    ]
                }
            },
        }
    },
    created() {
        this.getCateList()
    },
    methods: {
        async getCateList() {
            let data = await this.$axios.get("categories")
            if (data.data.meta.status !== 200) {
                return this.$message.error("获取商品分类数据失败")
            } else {
                this.cateList = data.data.data
                // console.log(this.cateList)
            }
        },
        // 级联选择器选中项变化触发
        handleChange() {
            // console.log(this.addForm.goods_cat)
            if (this.addForm.goods_cat.length !== 3) {
                this.addForm.goods_cat = []
            }
        },
        beforeTabLeave(activeName, oldActiveName) {
            // console.log('即将离开的标签页',oldActiveName)
            // console.log('即将进入的标签页',activeName)
            // return false
            if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
                this.$message.error("请先选择商品分类")
                return false
            }
        },
        async tabClicked() {
            // 使用Vue的nextTick确保activeIndex已更新
            this.$nextTick(async () => {
                // 使用activeIndex来判断当前标签页
                if (this.activeIndex === '1') {
                    let data = await this.$axios.get(`categories/${this.cateId}/attributes`, {
                        params: {
                            sel: 'many'
                        }
                    })
                    if (data.data.meta.status !== 200) {
                        return this.$message.error("获取动态参数列表失败")
                    } else {
                        data.data.data.forEach(item => {
                            item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals
                                .split(',')
                        })
                        this.manyTableData = data.data.data
                        console.log(this.manyTableData)
                    }
                } else if (this.activeIndex === '2') {
                    let data = await this.$axios.get(`categories/${this.cateId}/attributes`, {
                        params: {
                            sel: 'only'
                        }
                    })
                    if (data.data.meta.status !== 200) {
                        return this.$message.error("获取静态参数列表失败")
                    } else {
                        this.onlyTableData = data.data.data
                    }
                }
            })
        },
        // 图片预览
        handlePreview(file) {
            this.previewPath = file.response.data.url
            this.previewVisible = true
        },
        // 移除图片
        handleRemove(file) {
            // 1获取要删除的图片临时路径
            const filePath = file.response.data.tmp_path
            // 2.找到对应索引值
            const i = this.addForm.pics.findIndex(x => {
                x.pic === filePath
            })
            // 3.调用splice方法，将图片移除
            this.addForm.pics.splice(i, 1)

        },
        // 监听图片上传成功
        handleSuccess(response) {
            // 1.拼接得到一个图片对象
            const picInfo = {
                pic: response.data.tmp_path
            }
            // 将图片信息对象push到pics中
            this.addForm.pics.push(picInfo)
            console.log(this.addForm)
        },
        add() {
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) {
                    return this.$message.error("请填写必要的表单项")
                } else {
                    const form = _.cloneDeep(this.addForm)
                    form.goods_cat = form.goods_cat.join(',')
                    //处理动态参数
                    this.manyTableData.forEach(item => {
                        const newInfo = {
                            attr_id: item.attr_id,
                            attr_value: item.attr_vals.join(' ')
                        }
                        this.addForm.attrs.push(newInfo)
                    })
                    //处理静态属性
                    this.onlyTableData.forEach(item => {
                        const newInfo = {
                            attr_id: item.attr_id,
                            attr_value: item.attr_vals
                        }
                        this.addForm.attrs.push(newInfo)
                    })
                    form.attrs = this.addForm.attrs

                    const data = await this.$axios.post('goods', form)
                    if (data.data.meta.status !== 201) {
                        return this.$message.error(data.data.meta.msg)
                    } else {
                        this.$message.success("添加商品成功")
                        this.$router.push('/index/goods')
                    }
                }
            })
        }
    },
    computed: {
        cateId() {
            if (this.addForm.goods_cat.length === 3) {
                return this.addForm.goods_cat[2]
            } else {
                return null
            }
        }
    }

}
</script>
<style lang="less" scoped>
.el-checkbox {
    margin: 10px !important;
}

.img {
    width: 100%;
}

/* 富文本编辑器样式 */
.my-quill-editor {
    margin-bottom: 20px;
}

.ql-toolbar {
    border: 1px solid #dcdfe6 !important;
    border-bottom: none !important;
}

.ql-container {
    border: 1px solid #dcdfe6 !important;
    min-height: 300px;
}

/* 按钮样式 */
.btnAdd {
    margin-top: 20px;
}
</style>